package com.sd365.common.util;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
/**
 * @class TokenUtil
 * @classdesc  abel.zhan 规范注释   修改为 private static final
 * @author Administrator
 * @date 2021-12-7  22:37
 * @version 1.0.0
 * @see
 * @since
 */
public class TokenUtil {
     private static final Base64.Decoder DECODER = Base64.getDecoder();
     private static final Base64.Encoder ENCODER = Base64.getEncoder();

    /**
     * @param jsonToken:String
     * @return 返回已经经过加密的了token字符串
     */
    public static String encoderToken(String jsonToken) {
        final String[] split = jsonToken.split("\\.");
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : split) {
            final String tmp = encoder64(s);
            stringBuilder.append(tmp).append(".");
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder.toString();
    }

    /**
     * @param token:String
     * @return 返回token：head,payload, Signature的集合对象
     */
    public static List<String> decryptToken(String token) {
        final String[] split = token.split("\\.");
        List<String> list = new ArrayList<>();
        for (String s : split) {
            final String s1 = decoder64(s);
            list.add(s1);
        }
        return list;
    }

    private static String decoder64(String baseString) {
        final byte[] textByte = baseString.getBytes(StandardCharsets.UTF_8);
        return new String(DECODER.decode(textByte), StandardCharsets.UTF_8);
    }

    private static String encoder64(String baseString) {
        return ENCODER.encodeToString(baseString.getBytes(StandardCharsets.UTF_8));
    }

    private TokenUtil() {
    }
}
